import React from 'react'
//导入相关的组件
import { Toast } from 'antd-mobile';
//导入scss样式
import './index.scss'
//导入axios
import axios from 'axios'
//导入utils里面的获取定位城市的函数
import { getCurrentCity } from '../../utils/index'
//从react virtualized 中导入List组件
import { List, AutoSizer } from 'react-virtualized'
//导入NavHeader组件
import NavHeader from '../../components/NavHeader'
// List data as an array of strings
//const list = Array(100).fill('太宰治')



export default class CityList extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            //城市列表数据
            cityList: null,
            cityIndex: [],
            activeIndex: 0
        }
        // 索引（A、B等）的高度
        this.TITLE_HEIGHT = 36
        // 每个城市名称的高度
        this.NAME_HEIGHT = 50
        //创建list的ref
        this.list = React.createRef()
        // 有房源的城市
        this.HOUSE_CITY = ['北京', '上海', '广州', '深圳']
    }


    async componentDidMount() {
        await this.getCityList()
        //注意一开始this.getCityList()是异步任务，如果不用await，会先计算List 中每一行的高度，这个时候List 都还没有渲染出来，就会报错！
        // 调用 measureAllRows，提前计算 List 中每一行的高度，实现 scrollToRow 的精确跳转
        this.list.current.measureAllRows()
    }
    //获取城市列表和城市列表的索引
    getCityInfo(val) {
        const cityList = {}
        val.forEach(item => {
            const first = item.short.substr(0, 1)
            if (cityList[first]) {
                cityList[first].push(item)
            } else {
                cityList[first] = []
            }
        })
        const cityIndex = Object.keys(cityList).sort()
        return {
            cityList,
            cityIndex
        }

    }
    //获取热门城市数据
    async getHotCity() {
        const { data: res } = await axios.get('http://localhost:8080/area/hot')
        if (res.status !== 200) {
            console.error(res.description);
            return
        }
        return res.body
    }

    //获取城市列表数据
    async getCityList() {
        const { data: res } = await axios.get('http://localhost:8080/area/city', {
            params: {
                level: 1
            }
        })
        if (res.status !== 200) {
            console.error(res.description);
            return
        }
        const { cityList, cityIndex } = this.getCityInfo(res.body)
        const hotCity = await this.getHotCity()
        cityList.hot = hotCity
        cityIndex.unshift('hot')
        const currentCity = await getCurrentCity()
        cityList['#'] = [currentCity]
        cityIndex.unshift('#')
        this.setState(() => {
            return {
                cityList,
                cityIndex
            }
        })
    }

    //封装处理cityIndex数据
    formatIndex(key) {
        switch (key) {
            case '#':
                key = '当前定位'
                return key
            case 'hot':
                key = '热门城市'
                return key

            default:
                key = key.toUpperCase()
                return key
        }
    }

    //动态计算每一行高度的方法
    //每行的高度= 索引的高度 + cityList[cityIndex[index]].length*每个城市名称的高度
    getRowHeight = ({ index }) => {
        //console.log(index);
        const num = this.state.cityList[this.state.cityIndex[index]].length
        return this.TITLE_HEIGHT + num * this.NAME_HEIGHT
    }

    //切换城市的函数
    changeCity({ label, value }) {
        if (this.HOUSE_CITY.indexOf(label) !== -1) {
            localStorage.setItem('now_city', JSON.stringify({ label, value }))
            //跳回到home页面
            this.props.history.go(-1)
        } else {
            Toast.info('该城市暂无房源资源！', 1, null, false);
        }
    }

    //渲染长列表的事件处理函数
    rowRenderer = ({
        key, // 唯一key值
        index, // 索引号
        style, // 重点属性！！一定要给每一行数添加该样式
    }) => {
        const { cityList, cityIndex } = this.state
        const letter = cityIndex[index]
        return (
            <div key={key} style={style} className='city'>
                <div className='title'>{this.formatIndex(letter)}</div>
                {cityList[letter].map(item => (
                    <div
                        className="name"
                        key={item.value}
                        onClick={() => this.changeCity(item)}
                    >
                        {item.label}
                    </div>
                ))}
            </div>
        );
    }


    //渲染右侧索引列表的事件处理函数
    renderCityIndex() {
        return this.state.cityIndex.map((item, index) => {
            return (
                <li className='city-index-item ' key={item} onClick={() => this.list.current.scrollToRow(index)}>
                    <span className={index === this.state.activeIndex ? 'index-active' : ''}>{item === 'hot' ? '热' : item.toUpperCase()}</span>
                </li>
            )
        })
    }

    //翻动页面的时候触发的函数
    refreshRender = ({ startIndex }) => {
        if (startIndex !== this.state.activeIndex) {
            this.setState(() => {
                return {
                    activeIndex: startIndex
                }
            })
        }
    }



    // componentDidUpdate(prevProps) {
    //     if (prevProps.count !== this.props.count) {
    //         //this.setState({})
    //     }
    // }

    // shouldComponentUpdate() { }

    // componentWillUnmount() { }

    render() {
        return (
            <div className='cityList'>
                {/* 导航栏 */}
                <NavHeader className='navBar'>城市选择</NavHeader>
                {/* 长列表 */}
                <AutoSizer>
                    {({ height, width }) => (
                        <List
                            scrollToAlignment='start'
                            ref={this.list}
                            height={height}
                            rowCount={this.state.cityIndex.length}
                            rowHeight={this.getRowHeight}
                            rowRenderer={this.rowRenderer}
                            onRowsRendered={this.refreshRender}
                            width={width}
                        />
                    )}
                </AutoSizer>
                {/* 右侧索引列表 */}
                <ul className="city-index">
                    {
                        this.renderCityIndex()
                    }
                </ul>
            </div>
        )
    }
}
